package hp.com.servlet.ProductServlet;

import hp.com.entity.Product;
import hp.com.entity.Sells;
import hp.com.entity.Suk_Options;
import hp.com.entity.Users;
import hp.com.service.ProductService;
import hp.com.service.impl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/details")
public class ProductDetailsServlet extends HttpServlet {
    ProductService ps = new ProductServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过Session获得顶端用户对象并传为Arrtitube
        HttpSession session = req.getSession();
        Users user = (Users)session.getAttribute("userSession");
        req.setAttribute("userSession",user);
        //创建对象
        ProductService ps = new ProductServiceImpl();
        int id =Integer.parseInt(req.getParameter("id"));
        Product pdt = null;
        try {
            pdt = ps.GetProductById(id);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        //获取链接里的商品编号
        req.setAttribute("product",pdt);
        //分割商品大图链接
        String[] mainPic = pdt.getPicname().split(",");
        //分割商品属性
        String[] goodDetail = pdt.getDetailinformation().split(",");
        //分割商品详情图片
        String[] picDetail = pdt.getDetailpics().split(",");
        //获取商品属性信息
        try{
            List<Suk_Options> list = ps.getSUKOptionsByGoodId(id);
            req.setAttribute("optionList",list);
        }catch (Exception e){
            e.printStackTrace();
        }
        //获取商品价格初始显示
        String defaultPrice="";
        try{defaultPrice=ps.GetLowestAndHighestPrice(id);}catch (Exception e){
            e.printStackTrace();
        }
        //获取随机5个同类商品
        List<Sells> recommendation = new ArrayList<>();
        try {
            recommendation = ps.getRecommendation(pdt.getCategory(),5);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //转发及转发前准备
        req.setAttribute("recommendation",recommendation);
        req.setAttribute("defaultPrice",defaultPrice);//初始显示价格
        req.setAttribute("picDetail",picDetail);//详情图片链接
        req.setAttribute("mainPics",mainPic);//主图链接
        req.setAttribute("goodDetail",goodDetail);//商品属性
        req.getRequestDispatcher("/ShopPage/Product.jsp").forward(req,resp);
    }
}
